package cn.edu.thu.tsquality.core.algorithm.window.mean;

import cn.edu.thu.tsquality.core.common.algorithm.IAlgorithm;
import cn.edu.thu.tsquality.core.common.table.Header;
import cn.edu.thu.tsquality.core.common.table.Row;
import cn.edu.thu.tsquality.core.common.table.Table;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// 滑动平均修复：
// 对于每个要修复的数据，用它前面一些时刻数据的平均值作为此时刻数据的修复值
public class WindowMean implements IAlgorithm
{
    private Integer windowSize;

    WindowMean(Integer windowSize)
    {
        this.windowSize = windowSize;
    }

    private void println(String str)
    {
        System.out.println(str);
    }

    private void print(String str)
    {
        System.out.print(str);
    }

    public Table run(Table table)
    {
        List tableAttrList = Arrays.asList(table.getHeader().toArray());

        if (tableAttrList.size() !=1 && tableAttrList.size()!= 2)
            throw new IllegalArgumentException("table columns error, expected 1/2 columns");
        List<Row> tableRowsList = table.getRows();
        int inputDataSize = tableRowsList.size();

        double[] attrData = new double[inputDataSize];
        boolean[] needRepair = new boolean[inputDataSize];

        for (int i = 0; i < inputDataSize; i++)
        {
            // 第一列为空，或第二列值不为0，需要进行修复
            if (tableRowsList.get(i).get(0).equals(""))
            {
                attrData[i] = 0.0;
                needRepair[i] = true;
            }
            else
            {
                attrData[i] = Double.parseDouble((String) tableRowsList.get(i).get(0));
                if (table.getHeader().size() == 2 && Integer.parseInt((String) tableRowsList.get(i).get(1)) != 0)
                    needRepair[i] = true;
                else
                    needRepair[i] = false;

            }
        }

        //----------------
//        println(tableAttrList.toString());
//
//        println(windowSize+"");
//
//        println(inputDataSize+"");
//        print("data = [");
//        for(Double i : attrData)
//            print(i+" ");
//        println("]");
        //-----------------


        // 定义返回数据
        Header returnHeader = new Header(new String[] { (String)tableAttrList.get(0), "cleaned_"+tableAttrList.get(0)});
        List<Row> returnRows = new ArrayList<>();


        for(int i = 0; i < inputDataSize; i++)
        {
            // 进行修复
            if (needRepair[i])
            {
                double repairedValue = 0;
                for(int j = i - windowSize; j < i; j++)
                    repairedValue += (j >= 0? attrData[j] : attrData[0]);
                attrData[i] = repairedValue / windowSize;
            }

            returnRows.add(new Row(returnHeader, new String[] {
                    (String)tableRowsList.get(i).get(0),
                    String.format("%.3f", attrData[i])}, i));
        }
        return new Table(returnHeader, returnRows);
    }
}

